﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Z.Nlayer.Utility;
using Z.Nlayer.Utility.Encrypt;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Z.Nlayer.Infrastructure.Utility.BaseEnums;
using HttpContext = Microsoft.AspNetCore.Http.HttpContext;

namespace Company.Project.Web.Api.Lib
{
    public class CustomerConvertMiddleware
    {
        private readonly RequestDelegate _requestDelegate;
        public CustomerConvertMiddleware(RequestDelegate requestDelegate)
        {
            _requestDelegate = requestDelegate;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                string responseData;
                using (var reader = new StreamReader(context.Request.Body))
                {
                    responseData = await reader.ReadToEndAsync();
                }
                if (responseData != "")
                {
                    context.Items["ApiParmer"] = responseData;
                }
                await _requestDelegate.Invoke(context);
            }
            catch (Exception e)
            {
                var result = new APITipResult();
                if (e.GetBaseException().GetType() == typeof(CustomException))
                {
                    var custexception = ((CustomException)e.GetBaseException());
                    result.code = custexception.code == 0 ? Enum_ApiResultCode.OtherErr.GetValueToInt() : custexception.code;
                    result.message = custexception.message ?? custexception.Message;
                }
                else
                {
                    result.code = Enum_ApiResultCode.OtherErr.GetValueToInt();
                    result.message = e.InnerException?.Message ?? e.Message;
                }
                await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
            }
        }
    }
}
